package com.ljcalc.business.components.fetchers;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;

import com.ljcalc.business.components.ConnectionFactory;
import com.ljcalc.business.components.requests.IntegerUserRequest;

public class HTTPFetcher extends ContentFetcher {

	private LinkedList<Long> elementList = null;
	
	public HTTPFetcher(String url) {
		super(url);
	}

	
	public LinkedList<Long> getContent(){
		return (LinkedList<Long> )elementList.clone();
	}

	public int loadContent() throws IOException {
		if(url==null||!goodUrlFormat)
			return 0;
		elementList = new LinkedList<Long>();
		
		URLConnection connection = ConnectionFactory.createURLConnection(url) ;
		connection.connect();
		BufferedInputStream bin = new BufferedInputStream(url.openStream());
        Reader reader = new InputStreamReader(new BufferedInputStream(url.openStream())); 
        BufferedReader bufferedReader = new BufferedReader(reader);
        
        int ic;
		long start = 0;
        while ((ic = bufferedReader.read()) != -1) {
        	Character c = new Character((char)ic);
            if(!Character.isWhitespace(c.charValue())){
          	  int temp = Integer.parseInt(c.toString());
          	  start = start*10+temp;
            }else if(start!=0){
          	  elementList.add(new Long(start));
          	  start = 0;
            }
        }

		return 1;
		
	}

	public void setUserRequest(IntegerUserRequest ur) {
		try {
			this.url = new URL(ur.getURLStr());
			this.goodUrlFormat = true;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			this.goodUrlFormat = false;
			e.printStackTrace();
			
		}
		
	}

}
